package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

public class Sender implements Runnable{
    private DatagramSocket sender;
    private BufferedReader reader;
    private DatagramPacket packet;
    private static final int MAX_RECEIVE_BUFFER = 1024;
    private int localPort;//本进程端口
    private String targetIP;//目标主机IP
    private int targetPort;//目标主机端口

    public Sender(int localPort,String targetIP,int targetPort){
        this.localPort = localPort;
        this.targetIP = targetIP;
        this.targetPort = targetPort;
        try {
            sender = new DatagramSocket(localPort);//创建发送端
            reader = new BufferedReader(new InputStreamReader(System.in));//创建文本输入器
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @Override
    //接收数据包
    public void run() {
        String input;
        try {
            while (true) {
                input = reader.readLine();
                byte[] datas = input.getBytes();
                packet = new DatagramPacket(datas,0,datas.length,
                        new InetSocketAddress(this.targetIP,this.targetPort));
                sender.send(packet);
                if (input.equals("exit")||input.equals("bye")){
                    System.out.println("聊天结束");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sender.close();
        try {
            if(reader!=null){
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

